<?php

namespace App\Models\Traits;

use Carbon\Carbon;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Validation\ValidationException;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Rainsens\Dinglog\Facades\Dinglog;
use App\Models\RelationUser;


trait HasUserTeam
{
	public function myDownOneChildren($scope = null, $keyword = ''): HasMany
	{
		$children = $this->children();
		if ($scope === 'valid') {
			$children = $children->where(function (Builder $query) {
				$query->where('order_num','>',0);
			});
		}elseif($scope =='commander'){

			$children = $children->where('grade','commander');
		}elseif($scope =='seniorCommander'){

			$children = $children->where('grade','senior_commander');
		}

		if ($keyword) {
			$children = $children->where(function (Builder $query) use ($keyword) {
				$query->where('id', $keyword)
					->orWhere('phone', $keyword)
					->orWhere('name', 'like', "%{$keyword}%")
					->orWhere('nickname', 'like', "%{$keyword}%");
			});
		}

		return $children;
	}

	


	public function myDownChildrenNum()
	{
		$children = $this->children();
		$num = $children->where('is_locked', false)->count();
		
		return $num;
	}


	public function myDownChildrenReward()
	{
		/*$children = $this->children();
		$money = $children->where('is_locked', false)->sum('dividend_parent_reward');

		$dividend_team_reward = (string)$this->dividend_team_reward;
		if($dividend_team_reward > 0 ){

			$money = $dividend_team_reward + $money;
		}*/

		$money = $this->goldCoins()->where(function (Builder $query) {
				$query->where("remark","gold_record_team_prize")
					->orWhere("remark","gold_record_direct_prize")
					->orWhere("remark","support_team_coins")
					->orWhere("remark","support_prize_coins");
			})->sum("money");
		
		return sprintf("%.2f",$money);
	}

	public function myDownChildrenRewardYesterday()
	{
		/*$children = $this->children();
		$money = $children->where('is_locked', false)->sum('dividend_parent_reward');

		$dividend_team_reward = (string)$this->dividend_team_reward;
		if($dividend_team_reward > 0 ){

			$money = $dividend_team_reward + $money;
		}*/

		$money = $this->goldCoins()->where(function (Builder $query) {
				$query->where("remark","gold_record_team_prize")
					->orWhere("remark","gold_record_direct_prize")
					->orWhere("remark","support_team_coins")
					->orWhere("remark","support_prize_coins");
			})->whereDate("created_at",Carbon::yesterday())->sum("money");
		
		return sprintf("%.2f",$money);
	}

	public function myOrderChildren()
	{
		return $this->children()
			->where('order_num',">",0);
	}

	public function myCommanderChildrenNormal()
	{
		return $this->children()->where('grade','commander');
	}

	public function myCommanderChildrenSenior()
	{
		return $this->children()->where('grade','senior_commander');
	}

	public function myCommanderChildren()
	{
		return $this->children()->where(function (Builder $query) {
				$query->where('grade','commander')->orWhere('grade','senior_commander');
			});
	}

	public function myVipChildren()
	{
		return $this->children()
			->where('grade', 'vip')
			->where('is_locked', false)
			->where('vip_expired_at',">",Carbon::now());
	}

	public function myStarChildrenCount()
	{
		return $this->children()
			->where('grade', 'vip')
			->where('is_locked', false)
			->where('vip_expired_at',">",Carbon::now())->count();
	}

	public function myStarChildrenLevelCount()
	{
		return 0;
	}

	public function myNoStarChildren()
	{
		return $this->children()
			->where('is_locked', false);
	}


	public function myTeam()
	{
		return $this->relationUsers()->join('users','users.id','relation_users.user_id')
			->select('relation_users.*')
			->where('relation_users.team_level',"<=",6)
			->where('users.is_locked', false);
	}


	public function myChildren()
	{
		return $this->children()
			->where('is_locked', false);
	}

	public function mySecondTeam()
	{
		return $this->relationUsers()->join('users','users.id','relation_users.user_id')
			->select('relation_users.*')
			->where('users.is_locked', false)->where('relation_users.team_level',">=",2)->where('relation_users.team_level',"<=",6);
	}

	public function myValidTeam()
	{
		return $this->relationUsers()->join('users','users.id','relation_users.user_id')
			->select('relation_users.*')
			->where('users.is_locked', false)
			->where('users.grade', 'vip')
			->where('users.vip_expired_at',">",Carbon::now());
	}

	public function oneLevelTeamSeconds()
	{
		
		$children = $this->myDownOneChildren()->get();


		$oneTeamSeconds = big_decimal(0);
		foreach($children as $child){

			
			$oneTeamSeconds = $oneTeamSeconds->plus($child->ownOneSeconds());
			
		}

		$oneLevelPercent = cs('sale')->vip_one_level_brokage_percent / 100;
		if($oneTeamSeconds){
			
			return  $oneTeamSeconds->multipliedBy($oneLevelPercent);
		
		}

		

		return $oneTeamSeconds;


	}


	public function moreLevelTeamSeconds($i)
	{
		$children = $this->myValidTeam()->where('relation_users.team_level',$i)->get();

		$moreTeamSeconds = big_decimal(0);
		foreach($children as $child){
			$moreTeamSeconds = $moreTeamSeconds->plus($child->user->ownOneSeconds());
		}
		if($i!=2){

			$moreLevelPercent = cs('sale')->vip_more_level_brokage_percent / 100;
		}else{
			$moreLevelPercent = cs('sale')->vip_two_level_brokage_percent / 100;

		}
	
		if($moreTeamSeconds){

			return  $moreTeamSeconds->multipliedBy($moreLevelPercent);
		
		}

		return $moreTeamSeconds;

	}

	public function moreLevelTeamDay($i)
	{
		$children = $this->myValidTeam()->where('relation_users.team_level',$i)->get();

		$moreTeamSeconds = big_decimal(0);
		foreach($children as $child){
			$moreTeamSeconds = $moreTeamSeconds->plus($child->user->ownOneDays());
		}
		if($i==1){
			$moreLevelPercent = cs('sale')->vip_one_level_brokage_percent / 100;
		}elseif($i==2){

			$moreLevelPercent = cs('sale')->vip_two_level_brokage_percent / 100;
		}else{
			$moreLevelPercent = cs('sale')->vip_more_level_brokage_percent / 100;

		}
	
		if($moreTeamSeconds){

			return  $moreTeamSeconds->multipliedBy($moreLevelPercent);
		
		}

		return $moreTeamSeconds;

	}



	public function myValidChildren()
	{
		return $this->children()
			->where('grade', 'vip')
			->where('is_locked', false)
			->where("user_level",">",0)
			->where('vip_expired_at',">",Carbon::now());
	}

	public function needValidGoldStormChildrenForUpgrade()
	{
		$requiredChildren = sc('each_upgrade_needs_children');
		$needChildren = $requiredChildren - $this->myValidGoldStormChildren()->count();
		return $needChildren > 0 ? $needChildren : $requiredChildren;
	}

	public function myTargetGoldPrizeParents()
	{
		$parents = collect();
		$currentUser = $this->parent;
		$demandPrizeParentsAmount = (int)cs('storm')->child_record_give_team_parent_masters_amount;

		if ($demandPrizeParentsAmount <= 0) return $parents;
		
		while (true) {
			if (!$currentUser or $parents->count() >= $demandPrizeParentsAmount) {
				break;
			}
			//if ($currentUser->hasValidGoldRecord()) {
				$parents->push($currentUser);
			//}
			$currentUser = $currentUser->parent;
		}
		return $parents;
	}

	public function setChildNickname(User $user)
	{
		//Dinglog::text($this->id);
		Dinglog::text($user->id);
		if (!$user->parent or $user->parent_id !== $this->id) {
			fail('仅可备注属于自己团队成员');
		}
	    request()->validate(['nickname' => 'nullable|string|min:1|max:20']);
		$user->update(['nickname' => request('nickname')]);
		$user->setNickName(request('nickname'));
	}

	public function dayBonusTop100()
	{
		return self::query()
			->select('id')
			->where('grade', 'vip')
			->where('is_locked', false)
			->where('dividend_day', '>', 0)
			->orderByDesc('dividend_day')
			->orderBy('id')->take(100)
			->get()->pluck('id');
	}

	public function allBonusTop100()
	{
		return self::query()
			->select('id')
			->where('grade', 'vip')
			->where('is_locked', false)
			->where('dividend_all', '>', 0)
			->orderByDesc('dividend_all')
			->orderBy('id')->take(100)
			->get()->pluck('id');
	}

	public function djUser($child)
	{


		return $this->dj($child);
		
	}


	public function dj($child)
	{
		if($child->parent_id == $this->id){

			return true;
		}elseif(empty($child->parent_id)){
			return false;
		}else{

			$child = User::find($child->parent_id);

			return $this->dj($child);
		}

	}


	public function addTeamRelationUser()
	{
		$parentId = $this->parent_id;
		$userId = $this->id;
		$i = 1;
		$thisUserRelation = RelationUser::where('parent_id',$userId)->get();
		$createData = [];
		if($thisUserRelation){
			foreach($thisUserRelation as $v){
				$createData[] = [
					'user_id'=>$v['user_id'],
					'team_level'=>$v['team_level'] + 1,
					'parent_id'=>$parentId
				];
			}
			RelationUser::insert($createData);


		}
		return $this->addDj($parentId,$i,$userId);
	}

	public function addDj($parentId,$i,$userId)
	{

		if($parentId){
			RelationUser::create(['user_id'=>$userId,'team_level'=>$i,'parent_id'=>$parentId]);
			$i++;
			$parent = User::find($parentId);
			
			return $this->addDj($parent->parent_id , $i,$userId);
		}else{

			return false;
		}

	}

}
